<template>
  <view class="page-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-left">
        <view class="back-btn" @click="goBack">
          <uni-icons type="left" size="20" color="#333333" />
        </view>
        <view class="home-btn" @click="goHome">
          <uni-icons type="home" size="20" color="#333333" />
        </view>
      </view>
      <text class="nav-title">推荐医生</text>
    </view>

    <!-- 筛选区域 -->
    <view class="filter-wrapper">
      <view class="filter-row">
        <view class="filter-btn" @click="handleFilter(0)">
          <text :style="{ color: currentFilter === 0 ? '#4A90E2' : '#333' }">综合排序</text>
          <uni-icons :type="currentFilter === 0 ? 'top' : 'bottom'" size="12" :color="currentFilter === 0 ? '#4A90E2' : '#333'" />
        </view>
        <view class="filter-btn" @click="handleFilter(1)">
          <text :style="{ color: currentFilter === 1 ? '#4A90E2' : '#333' }">评分最高</text>
          <uni-icons :type="currentFilter === 1 ? 'top' : 'bottom'" size="12" :color="currentFilter === 1 ? '#4A90E2' : '#333'" />
        </view>
        <view class="filter-btn" @click="handleFilter(2)">
          <text :style="{ color: currentFilter === 2 ? '#4A90E2' : '#333' }">接诊最多</text>
          <uni-icons :type="currentFilter === 2 ? 'top' : 'bottom'" size="12" :color="currentFilter === 2 ? '#4A90E2' : '#333'" />
        </view>
        <view class="filter-btn" @click="handleFilter(3)">
          <text :style="{ color: currentFilter === 3 ? '#4A90E2' : '#333' }">筛选</text>
          <uni-icons type="filter" size="14" :color="currentFilter === 3 ? '#4A90E2' : '#333'" />
        </view>
      </view>
    </view>

    <!-- 医生列表 -->
    <scroll-view 
      class="doctor-list" 
      scroll-y
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
      @refresherrestore="onRestore">
      <DoctorCard
        v-for="(doctor, index) in doctorList"
        :key="index"
        :doctor="doctor"
        @consult="handleConsult"
      />
    </scroll-view>

    <!-- 筛选弹窗 -->
    <uni-popup ref="filterPopup" type="bottom" background-color="#fff">
      <view class="filter-popup">
        <view class="filter-popup-header">
          <text class="filter-popup-title">筛选条件</text>
          <text class="filter-popup-close" @click="closeFilter">关闭</text>
        </view>
        
        <!-- 科室筛选 -->
        <view class="filter-section-title">科室</view>
        <view class="filter-tags">
          <text 
            v-for="dept in departments" 
            :key="dept"
            :class="['filter-tag', { active: selectedDepartment === dept }]"
            @click="selectDepartment(dept)"
          >{{ dept }}</text>
        </view>
        
        <!-- 职称筛选 -->
        <view class="filter-section-title">职称</view>
        <view class="filter-tags">
          <text 
            v-for="title in titles" 
            :key="title"
            :class="['filter-tag', { active: selectedTitle === title }]"
            @click="selectTitle(title)"
          >{{ title }}</text>
        </view>
        
        <!-- 按钮区域 -->
        <view class="filter-buttons">
          <button class="reset-btn" @click="resetFilter">重置</button>
          <button class="confirm-btn" @click="confirmFilter">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import DoctorCard from './components/DoctorCard.vue';
import { apiBaseUrl, minioBaseUrl } from '../../config/api'

interface Doctor {
  id: number;
  name: string;
  title: string;
  department: string;
  specialty: string;
  rating: number;
  consult_count: number;
  avatar: string;
}

// 筛选选项
const filterItems = ['综合排序', '评分最高', '接诊最多', '筛选'];
const currentFilter = ref(0);

// 医生列表数据
const doctorList = ref<Doctor[]>([]);

// 筛选相关数据
const filterPopup = ref<{
  open: () => void;
  close: () => void;
}>();
const departments = ref(['全部', '内科', '外科', '儿科', '妇产科']);
const titles = ref(['全部', '主任医师', '副主任医师', '主治医师']);
const selectedDepartment = ref('全部');
const selectedTitle = ref('全部');
const originalDoctorList = ref<Doctor[]>([]);

// 下拉刷新状态
const isRefreshing = ref(false);

// 获取医生列表数据
const getDoctorList = async () => {
  try {
    // 只在非刷新状态下显示loading
    if (!isRefreshing.value) {
      uni.showLoading({
        title: '加载中...'
      });
    }
    
    const [err, res] = await uni.request({
      url: `${apiBaseUrl}/doctors/selectAll`,
      method: 'GET'
    }).then(res => [null, res]).catch(err => [err, null]);

    if (err) {
      throw new Error('网络请求失败');
    }

    const { code, result } = res.data as { code: number; result: Doctor[] };
    if (code === 200 && result) {
      doctorList.value = result;
    } else {
      uni.showToast({
        title: '获取医生列表失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('请求错误:', error);
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
    // 停止下拉刷新
    if (isRefreshing.value) {
      isRefreshing.value = false;
    }
  }
};

// 下拉刷新方法
const onRefresh = async () => {
  isRefreshing.value = true;
  await getDoctorList();
};

const onRestore = () => {
  console.log('刷新复位');
};

// 页面加载时获取数据
onMounted(() => {
  getDoctorList();
});

// 处理筛选
const handleFilter = (index: number) => {
  currentFilter.value = index;
  
  if (index === 3) {
    // 打开筛选弹窗
    if (filterPopup.value) {
      filterPopup.value.open();
    }
    return;
  }
  
  const doctors = [...doctorList.value];
  
  switch (index) {
    case 1: // 评分最高
      doctors.sort((a, b) => b.rating - a.rating);
      break;
    case 2: // 接诊最多
      doctors.sort((a, b) => b.consult_count - a.consult_count);
      break;
    default: // 综合排序（默认顺序）
      doctors.sort((a, b) => a.id - b.id);
  }
  
  doctorList.value = doctors;
};

// 关闭筛选弹窗
const closeFilter = () => {
  if (filterPopup.value) {
    filterPopup.value.close();
  }
};

// 选择科室
const selectDepartment = (dept: string) => {
  selectedDepartment.value = dept;
};

// 选择职称
const selectTitle = (title: string) => {
  selectedTitle.value = title;
};

// 重置筛选
const resetFilter = () => {
  selectedDepartment.value = '全部';
  selectedTitle.value = '全部';
};

// 确认筛选
const confirmFilter = () => {
  let filteredDoctors = [...originalDoctorList.value];
  
  // 应用科室筛选
  if (selectedDepartment.value !== '全部') {
    filteredDoctors = filteredDoctors.filter(
      doctor => doctor.department === selectedDepartment.value
    );
  }
  
  // 应用职称筛选
  if (selectedTitle.value !== '全部') {
    filteredDoctors = filteredDoctors.filter(
      doctor => doctor.title === selectedTitle.value
    );
  }
  
  doctorList.value = filteredDoctors;
  closeFilter();
};

// 处理咨询
const handleConsult = (doctor: Doctor) => {
  // 将医生信息转换为查询字符串
  const query = encodeURIComponent(JSON.stringify({
    id: doctor.id,
    name: doctor.name,
    department: doctor.department,
    title: doctor.title,
    avatar: doctor.avatar,
    specialty: doctor.specialty
  }));
  
  // 跳转到咨询页面
  uni.navigateTo({
    url: `/pages/consultation/chat?doctor=${query}`
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 返回首页
const goHome = () => {
  uni.switchTab({
    url: '/pages/index/index'
  });
};
</script>

<style>
.page-container {
  min-height: 100vh;
  background-color: #F5F8FF;
  padding-top: 140px;
  position: relative;
}

.nav-bar {
  position: fixed;
  top: 52px;
  left: 0;
  right: 0;
  height: 44px;
  background: #fff;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.filter-wrapper {
  position: fixed;
  top: 96px;
  left: 0;
  right: 0;
  height: 44px;
  background: #fff;
  z-index: 999;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.filter-row {
  display: flex;
  height: 100%;
  align-items: center;
  justify-content: space-around;
  background: #fff;
}

.filter-btn {
  flex: 1;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  background: #fff;
}

.doctor-list {
  margin-top: 20px;
  height: calc(100vh - 160px);
  padding: 10px 15px;
}

.nav-left {
  position: absolute;
  left: 30rpx;
  display: flex;
  gap: 20rpx;
}

.back-btn, .home-btn {
  width: 64rpx;
  height: 64rpx;
  background-color: #FFFFFF;
  border-radius: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.nav-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
}

.filter-popup {
  background-color: #FFFFFF;
  border-radius: 24rpx 24rpx 0 0;
  padding: 30rpx;
}

.filter-popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.filter-popup-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
}

.filter-popup-close {
  font-size: 28rpx;
  color: #999999;
}

.filter-section-title {
  font-size: 28rpx;
  color: #333333;
  margin: 20rpx 0;
}

.filter-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.filter-tag {
  padding: 12rpx 24rpx;
  background-color: #F5F8FF;
  border-radius: 100rpx;
  font-size: 26rpx;
  color: #666666;
}

.filter-tag.active {
  background-color: #4A90E2;
  color: #FFFFFF;
}

.filter-buttons {
  display: flex;
  gap: 20rpx;
  margin-top: 40rpx;
}

.reset-btn, .confirm-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.reset-btn {
  background-color: #F5F8FF;
  color: #666666;
}

.confirm-btn {
  background-color: #4A90E2;
  color: #FFFFFF;
}

.reset-btn:active, .confirm-btn:active {
  opacity: 0.8;
}
</style> 